package com.wwfish.cmsui.modules.system.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.*;
import com.nexustar.gwt.widgets.client.asyn.FishAsyncCallback;
import com.nexustar.gwt.widgets.client.asyn.IAsyncModelCallback;
import com.nexustar.gwt.widgets.client.asyn.LoadingAsyncCallback;
import com.nexustar.gwt.widgets.client.model.PaginationModelDto;
import com.nexustar.gwt.widgets.client.ui.button.MyButton;
import com.nexustar.gwt.widgets.client.ui.form.*;
import com.nexustar.gwt.widgets.client.ui.iprovider.IPaginationModelProvider;
import com.nexustar.gwt.widgets.client.ui.panel.InfoPanel;
import com.nexustar.gwt.widgets.client.ui.table.*;
import com.nexustar.gwt.widgets.client.ui.textbox.FishLabelListBox;
import com.nexustar.gwt.widgets.client.ui.textbox.FishLabelTextBox;
import com.nexustar.gwt.widgets.client.ui.toolbar.ToolBar;
import com.nexustar.gwt.widgets.client.ui.toolbar.ToolItem;
import com.nexustar.gwt.widgets.client.ui.window.IMessageConfirmCall;
import com.nexustar.gwt.widgets.client.ui.window.Message;
import com.nexustar.gwt.widgets.client.ui.window.PopPanel;
import com.wwfish.cms.model.GeneralCodeDto;
import com.wwfish.cms.service.CodeManager;
import com.wwfish.cmsui.modules.common.client.BaseCMSPage;
import com.wwfish.cmsui.modules.common.client.util.CodesHelper;
import com.wwfish.cmsui.modules.common.client.util.ServiceFactory;
import com.wwfish.gwt.reflection.client.ModelReflection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Tom
 * Date: 2010-8-24
 * Time: 9:27:31
 * To change this template use File | Settings | File Templates.
 */
public class CodeManagePage extends BaseCMSPage {

    private PaginationTable tableList;
//    private ContentPanel searchPanel;
    private FormContainer queryForm;
    private PopPanel pop;
    private FormContainer codeForm;
    private FishLabelListBox category_codeForm = new FishLabelListBox("代码类别:");
    private FishLabelListBox category_queryForm = new FishLabelListBox("代码类别:");
    private List categories = new ArrayList();

    public CodeManagePage() {
        setPageTitle("代码管理");
    }

    @Override
    protected boolean isRunAsync() {
        return true;
    }

    @Override
    public void initWidgets(final DockPanel page) {
        GWT.runAsync(new RunAsyncCallback() {
            public void onFailure(Throwable reason) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            public void onSuccess() {


                VerticalPanel dataPanel = new VerticalPanel();
                dataPanel.setWidth("100%");
                dataPanel.add(wrapMenuBar());
                initTableList();
//        ContentPanel tableListWrapper = new ContentPanel("人员信息列表");
//        tableListWrapper.setWidth("100%");
//        tableListWrapper.addContentWidget(tableList);
                dataPanel.add(tableList);

                Panel searchPanel = wrapSearchBlock();
                page.add(searchPanel, DockPanel.NORTH);
                page.setCellHeight(searchPanel, "30px");
                page.add(dataPanel, DockPanel.CENTER);
                initCodeForm();

                CodeManagePage.this.client.success(null);
            }
        });

    }

    private Widget wrapMenuBar() {
        ToolBar bar = new ToolBar();
        bar.setWidth("100%");

        ToolItem add = new ToolItem("新增代码");
        ToolItem edit = new ToolItem("编辑代码");
        ToolItem deactive = new ToolItem("冻结代码");
        ToolItem active = new ToolItem("激活代码");
        ToolItem delete = new ToolItem("删除代码");

        bar.addToolItem(add);
        bar.addToolItem(edit);
        bar.addToolItem(deactive);
        bar.addToolItem(active);
        bar.addToolItem(delete);

        add.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                pop.show();
                pop.center();
                pop.setWindowTitle("新增代码");
                codeForm.getModelManger().renderModel(new GeneralCodeDto());
            }
        });
        edit.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                if (tableList.getTable().getSelectedItem() != null) {
                    pop.show();
                    pop.center();
                    pop.setWindowTitle("编辑代码");
                    codeForm.getModelManger().renderModel(ModelReflection.clone(tableList.getTable().getSelectedItem().getUserObject()));
                }

            }
        });
        deactive.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                if (tableList.getTable().getSelectedItem() != null) {
                    final GeneralCodeDto code = (GeneralCodeDto) tableList.getTable().getSelectedItem().getUserObject();
                    code.setDisable(false);
                    ServiceFactory.invoke(CodeManager.class.getName(), "saveAndUpdate", new Object[]{code}, new LoadingAsyncCallback() {
                        @Override
                        protected void success(Object result) {
                            updateDmdl(code);
                            tableList.getTable().getSelectedItem().renderSelf();
                            InfoPanel.show("冻结代码！");
                        }
                    });
                }
            }
        });

        active.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent clickEvent) {
                final GeneralCodeDto code = (GeneralCodeDto) tableList.getTable().getSelectedItem().getUserObject();
                code.setDisable(false);
                ServiceFactory.invoke(CodeManager.class.getName(), "saveAndUpdate", new Object[]{code}, new LoadingAsyncCallback() {
                    public void success(Object result) {
                        updateDmdl(code);
                        tableList.getTable().getSelectedItem().renderSelf();
                        InfoPanel.show("激活代码！");
                    }
                });
            }
        });

        delete.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent clickEvent) {
                final TableItem selectedItem = tableList.getTable().getSelectedItem();
                if (selectedItem != null) {
                    Message.confirm("确认要删除?", "温馨提示", new IMessageConfirmCall() {
                        public void doExcute(boolean flag) {
                            if (flag) {
                                final GeneralCodeDto code = (GeneralCodeDto) selectedItem.getUserObject();
                                ServiceFactory.invoke(CodeManager.class.getName(), "delete", new Object[]{code}, new LoadingAsyncCallback() {
                                    public void success(Object result) {
                                        updateDmdl(code);
                                        tableList.getModelManger().renderAsyncModel(new Object[]{1, 20});
                                        InfoPanel.show("操作成功！");
                                    }
                                });
                            }
                        }
                    });
                }
            }
        });
        return bar;
    }

    @Override
    protected void ddOutPageModel(Object dto) {
        queryForm.getModelManger().renderModel(new HashMap(2));
//        tableList.getModelManger().renderAsyncModel(new Object[]{1, 20});   // 默认查询数据
    }


    private FlowPanel wrapSearchBlock() {
        FlowPanel searchPanel = new FlowPanel();
        searchPanel.setStyleName("codeManager_searchPanel");


        category_queryForm.setLabelWidth("100%");
        final MyButton queryButton = new MyButton("查询");

        initCodeType(category_queryForm);
        queryButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                tableList.getModelManger().renderAsyncModel(new Object[]{1, 20});
            }
        });
        queryForm = new FormContainer(2);
        queryForm.addElement(new FormElement(category_queryForm, new FormElementProviderAdpter() {
            public void getValue(Object object) {
                ((Map) object).put("category", category_queryForm.getValue());
            }

            public void setValue(Object object) {
                category_queryForm.setValue(((Map) object).get("category"));
            }
        }));

        queryForm.addWidget(queryButton);

        searchPanel.add(queryForm);
        return searchPanel;
    }

    private void initCodeType(final FishLabelListBox codeType) {
        if (categories.isEmpty()) {
            ServiceFactory.invoke(CodeManager.class.getName(), "getCodesByParentId", new Object[]{null}, new FishAsyncCallback() {
                public void onSuccess(Object result) {
                    categories = (List<GeneralCodeDto>) result;
                    setCategoryListBox(codeType);
                }
            });
        } else {
            setCategoryListBox(codeType);
        }
    }

    private void setCategoryListBox(FishLabelListBox codeType) {
        wrapCategory(categories);
        ((ListBox) codeType.getUI()).clear();
        for (Object s : categories) {
            ((ListBox) codeType.getUI()).addItem(((GeneralCodeDto) s).getName(), ((GeneralCodeDto) s).getCode());
        }
    }


    private void wrapCategory(List<GeneralCodeDto> category) {
        if (category != null) {
            if (category.size() == 0 || category.size() >= 0 && !"0".equals(category.get(0).getCode())) {
                GeneralCodeDto dmDl = new GeneralCodeDto();
                dmDl.setCode("0");
                dmDl.setName("代码大类");
                category.add(0, dmDl);
            }
        }
    }

    public void initTableList() {
        ViewTable table = new ViewTable(getColsWaiter());
        tableList = new PaginationTable(table, 20);
        tableList.getModelManger().setProvider(new IPaginationModelProvider() {
            public void setInputData(int begin, int count, final IAsyncModelCallback asyn) {

                ServiceFactory.invoke(CodeManager.class.getName(), "getPageEntities",
                        new Object[]{begin, count, (Map) queryForm.getModelManger().getModel()},
                        new FishAsyncCallback() {
                            public void onSuccess(Object result) {
                                asyn.setModelElments(result);
                            }
                        });
            }
        });
    }

    public void initCodeForm() {
        pop = new PopPanel();
        final FishLabelTextBox name = new FishLabelTextBox("代码名称:");
        final FishLabelTextBox code = new FishLabelTextBox("代码值:");
        category_codeForm = new FishLabelListBox("代码类别:");

//        name.setLabelWidth("55px");
//        code.setLabelWidth("55px");
//        category_codeForm.setLabelWidth("55px");

        initCodeType(category_codeForm);
        codeForm = new FormContainer(1);
        codeForm.addElement(new FormElement(name, new FormElementProviderAdpter() {
            public void setValue(Object object) {
                name.setValue(((GeneralCodeDto) object).getName());
            }

            public void getValue(Object object) {
                ((GeneralCodeDto) object).setName((String) name.getValue());
            }
        }, new IValidator[]{ValidatorCreator.require()}));
        codeForm.addElement(new FormElement(code, new FormElementProviderAdpter() {
            public void setValue(Object object) {
                code.setValue(((GeneralCodeDto) object).getCode());
            }

            public void getValue(Object object) {
                ((GeneralCodeDto) object).setCode((String) code.getValue());
            }
        }, new IValidator[]{ValidatorCreator.require()}));
        codeForm.addElement(new FormElement(category_codeForm, new FormElementProviderAdpter() {
            public void setValue(Object object) {
                category_codeForm.setValue(String.valueOf(((GeneralCodeDto) object).getParentId()));
            }

            public void getValue(Object object) {
                String categoryString = (String) category_codeForm.getValue();
                ((GeneralCodeDto) object).setParentId(Long.valueOf(categoryString));
            }
        }, new IValidator[]{ValidatorCreator.require()}));

        HorizontalPanel bb = new HorizontalPanel();
        MyButton save = new MyButton("保存");
        MyButton cancel = new MyButton("取消");
        bb.add(save);
        bb.add(new HTML("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"));
        bb.add(cancel);
        save.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                if (!codeForm.isValid()) return;
                final GeneralCodeDto generalCode = (GeneralCodeDto) codeForm.getModelManger().getModel();
                final boolean isAdd = generalCode.getId() == null;

                ServiceFactory.invoke(CodeManager.class.getName(), "saveAndUpdate", new Object[]{generalCode}, new LoadingAsyncCallback() {
                    public void success(Object result) {
                        Object object = tableList.getModelManger().getModel();
                        if (object != null) {
                            PaginationModelDto modelDto = (PaginationModelDto) object;
                            if (isAdd) {
                                modelDto.addModelItem(result, 0);
                            } else {
                                modelDto.modifyModelItem(result, codeForm.getModelManger().getModel());
                            }
                            tableList.getModelManger().renderModel(tableList.getModelManger().getModel());
                        }
                        updateDmdl(generalCode);
                        pop.hide();
                        InfoPanel.show("操作成功！");
                    }
                });


            }
        });
        cancel.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                pop.hide();
            }
        });

        codeForm.addWidget(bb, HasHorizontalAlignment.ALIGN_CENTER);

        pop.addWidget(codeForm);


    }

    private void updateDmdl(GeneralCodeDto generalCode) {
//        if (Constants.code_dl.equals(generalCode.getCategory()) && generalCode.isEnabled()) {  // 未激活的代码大类要不要显示？
//        if (Constants.code_dl.equals(generalCode.getCategory())) {  //代码大类操作
//            categories.clear();
//            initCodeType(category_codeForm);
//            initCodeType(category_queryForm);
//        }
    }

    private ColumnWaiter getColsWaiter() {

        ColumnExt co1 = new ColumnExt("代码名称", 200, new IColumnRender() {
            public void renderColumn(CellItem cell) {
                GeneralCodeDto temp = (GeneralCodeDto) cell.getUserObject();
                cell.setText(temp.getName());
            }
        });
        ColumnExt co2 = new ColumnExt("代码值", 100, new IColumnRender() {
            public void renderColumn(CellItem cell) {
                GeneralCodeDto temp = (GeneralCodeDto) cell.getUserObject();
                cell.setText(temp.getCode());
            }
        });
        ColumnExt co3 = new ColumnExt("代码类型", 300, new IColumnRender() {
            public void renderColumn(CellItem cell) {
                GeneralCodeDto temp = (GeneralCodeDto) cell.getUserObject();
                cell.setText(CodesHelper.getNameByCode(categories, String.valueOf(temp.getParentId())));
            }
        });
        ColumnExt co4 = new ColumnExt("状态", 150, new IColumnRender() {
            public void renderColumn(CellItem cell) {
                GeneralCodeDto temp = (GeneralCodeDto) cell.getUserObject();
                cell.setText(temp.getDisable() ? "冻结" : "可用");
            }
        });
        return new ColumnWaiter(new ColumnExt[]{co1, co2, co3, co4});
    }
}
